package com.cnjson.sensor.protocolARP.waterQualitySensorProtocol.dataReport;

import com.cnjson.sensor.db.dao.EquipmeDao;
import com.cnjson.sensor.db.dao.WaterDataDao;
import com.cnjson.sensor.db.entity.WaterData;
import com.cnjson.sensor.protocolARP.waterQualitySensorProtocol.WaterQualitySensorResolveInterface;
import com.cnjson.sensor.protocolARP.waterQualitySensorProtocol.response.WaterQualitySensorResponse;
import com.cnjson.sensor.util.ByteUtils;
import com.cnjson.sensor.util.DataFormater;
import com.mysql.jdbc.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.channels.SocketChannel;
import java.util.*;

@Component
public class DataReport implements WaterQualitySensorResolveInterface {


    private static final Logger logger = LoggerFactory.getLogger(DataReport.class);


    @Autowired
    private WaterDataDao waterDatadao;
    @Autowired
    private EquipmeDao equipmeDao;

    @Override
    public byte[] resolve(String[] data, SocketChannel client) {

        byte[] response = null;

        // 2位设备地址段
        String address =data[7]+data[8];


        String equipmentId = equipmeDao.findIdByNumber(address);  //ift_equipment WHERE number = ?
        if (StringUtils.isNullOrEmpty(equipmentId)) {
            System.out.println("---------0x47 设备未配置-------------");
            logger.warn("---------0x47 设备未配置-------------");
            return null;
        }


        String date=data[13]+data[14]+data[15]+data[16]+data[17]+data[18];
        byte[] dateBytes= ByteUtils.hexStringToBytes(date);
        Date sDate = DataFormater.bytesToDate(dateBytes);


        logger.info("-----------打印时间:" + sDate + "-----,设备地址---" + address);

        // SAVE TO DB.....
        try {
            // 通道数，一般固定为11个通道


            String number =data[19];
            int channelNum = Integer.valueOf(number, 16);
            logger.info("-----------通道数:" + channelNum);


            WaterData waterData = new WaterData();


            wrapWaterData(data, waterData,channelNum,sDate);

            //上报成功标示：0xCB 0xCE
            byte[] content = new byte[]{(byte) 0xCB, (byte) 0xCE};
            //4位地址
            String device=data[7]+data[8]+data[9]+data[10];
            byte[] deviceBytes= ByteUtils.hexStringToBytes(device);
            response = WaterQualitySensorResponse.buildResponsePackage((byte) 0x47, deviceBytes, content);

            logger.info("-----------0x47 接收设备上报数据并返回----------");
            waterDatadao.save(waterData);
            logger.info("-----------数据保存至数据库----------");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("----------0x47-----------" + e.getMessage());
        }
        return response;
    }



    private void wrapWaterData(String[] data, WaterData waterData,int num,Date date) {
        Map<String,Double> m=new HashMap<>();
        Double d = 0.0;

        for (int j=0;j<num;j++){
            try {

                String strres = data[j*4+20]+data[j*4+21]+data[j*4+22]+data[j*4+23];
                //获取检测的数据
                d = Double.longBitsToDouble(Integer.valueOf(strres, 16));
            } catch (Exception e) {
                logger.error("检测数据转换失败");
            }

            m.put("num_"+j,d);
            logger.info("通道 num_"+j+"获取到的数据为 "+d);
        }

        //**************  这里要改的，就是将map的数据一个个对应的（num_1、num_2）加到waterData
        waterData.buildammoniaNitrogen(m.get("num_1"));


        waterData.setAcquisitionTime(date);
        waterData.setUpdateTime(new Date());

    }
}
